﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Hosting;
using MvcEngine.Core;

namespace MvcEngine.Core
{
    public class ContentResolver : IContentResolver
    {
        public ContentResolver()
        {

        }

        public static IContentResolver Current 
        {
            get { return IoC.Resolve<IContentResolver>(); }
        }

        protected static readonly string[] scriptLocationFormats = new[]
        {
            "~/Skins/{1}/Content/Scripts/{0}",
            "~/Areas/{4}/Content/Scripts/{0}",
            "~/Modules/{3}/Areas/{4}/Content/Scripts/{0}",
            "~/Content/Scripts/{0}"
        };

        protected static readonly string[] cssLocationFormats = new[]
        {
            "~/Skins/{1}/Content/{0}",
            "~/Areas/{4}/Content/{0}",
            "~/Modules/{3}/Areas/{4}/Content/{0}",
            "~/Content/{0}",
            "~/Skins/{1}/Templates/{5}/{4}/Content/{0}"
        };

        protected static readonly string[] imagesLocationFormats = new[]
        {
            "~/Skins/{1}/Content/Images/{0}",
            "~/Areas/{4}/Content/Images/{0}",
            "~/Modules/{3}/Areas/{4}/Content/Images/{0}",
            "~/Content/Images/{0}"
        };

        public string GetImagePath(string relativePath, string area, string moduleName, out string[] locationsSearched)
        {
            return FindPath(imagesLocationFormats, relativePath, area, moduleName, out locationsSearched);
        }

        public string GetScriptPath(string relativePath, string area, string moduleName, out string[] locationsSearched)
        {
            return FindPath(scriptLocationFormats, relativePath, area, moduleName, out locationsSearched);
        }

        public string GetStyleSheetPath(string relativePath, string area, string moduleName, out string[] locationsSearched)
        {
            return FindPath(cssLocationFormats, relativePath, area, moduleName, out locationsSearched);
        }

        protected virtual string FindPath(string[] locationsToSearch, string relativePath, string area, string moduleName, out string[] locationsSearched)
        {
            int locationCount = 0;
            locationsSearched = new string[locationsToSearch.Length];

            foreach (string locationFormat in locationsToSearch)
            {
                string path = string.Format(locationFormat, relativePath, SiteContext.Current.Skin.Name, SiteContext.Current.Site.Name, moduleName, area, SiteContext.Current.SkinTemplate.Name);
                locationsSearched[locationCount++] = path;

                if (HostingEnvironment.VirtualPathProvider.FileExists(path))
                {
                    return path;
                }
            }

            return null;
        }
    }
}
